//
//  PopVC.swift
//  popTableVC
//
//  Created by 李煜 on 2022/9/15.
//

import UIKit

protocol PopVCDelegate {
  func select(viewController: UIViewController, index: Int)
}

class PopVC: UIViewController {
  lazy var datas: [String] = ["扫扫", "逛逛", "璐璐"]
  // 代理
  var delegate: PopVCDelegate?

  lazy var tableView: UITableView = {
    let table = UITableView(frame: view.bounds)
    table.delegate = self
    table.dataSource = self
    return table
  }()

  ///  便利构造函数

  convenience init(barbuttonItem: UIBarButtonItem?, sourceView: UIView?, sourceRect: CGRect?) {
    self.init()

    modalPresentationStyle = .popover
    preferredContentSize = .init(width: 100, height: 120)
    popoverPresentationController?.delegate = self

    if let item = barbuttonItem {
      popoverPresentationController?.barButtonItem = item
    } else if let sourceView = sourceView {
      popoverPresentationController?.sourceView = sourceView
      popoverPresentationController?.sourceRect = sourceRect ?? sourceView.bounds
    }
  }

  override func viewDidLoad() {
    super.viewDidLoad()
    view.addSubview(tableView)
  }
}

extension PopVC: UITableViewDelegate, UITableViewDataSource {
  func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    delegate?.select(viewController: self, index: indexPath.row)
  }

  func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    datas.count
  }

  func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let id = "popID"
    var cell = tableView.dequeueReusableCell(withIdentifier: id)
    if cell == nil {
      cell = UITableViewCell(style: .default, reuseIdentifier: id)
    }
    cell?.textLabel?.text = datas[indexPath.row]

    return cell!
  }
}

extension PopVC: UIPopoverPresentationControllerDelegate {
  func adaptivePresentationStyle(for controller: UIPresentationController) -> UIModalPresentationStyle {
    .none
  }
}
